package com.lesama.lock;

/*
    同步方法：
        在方法的返回值类型前加入synchronized关键字
    静态方法： 锁对象是字节码对象
    非静态方法： 锁对象是this
 */

public class ThreadTest3 {
    public static void main(String[] args) {
        SellTicketsTask3 task3 = new SellTicketsTask3();

        Thread t1 = new Thread(task3, "线程1");
        Thread t2 = new Thread(task3, "线程2");
        Thread t3 = new Thread(task3, "线程3");

        t1.start();
        t2.start();
        t3.start();
    }
}

class SellTicketsTask3 implements Runnable {

    private int tickets = 10000;

    @Override
    public void run() {
        while(true) {
            String name = Thread.currentThread().getName();
            if(name.equals("线程1") || name.equals("线程3")) {
                if (method()) {
                    break;
                }
            } else if(name.equals("线程2")) {
                synchronized (this) {
                    if(tickets == 0) {
                        break;
                    }
                    System.out.println(Thread.currentThread().getName() + "售出了第" + tickets + "张票");
                    tickets--;
                }
            }

        }
    }

    private synchronized boolean method() {
        if(tickets == 0) {
            return true;
        }
        System.out.println(Thread.currentThread().getName() + "售出了第" + tickets + "张票");
        tickets--;
        return false;
    }
}